﻿using DBModels;
using Method.DateTime;
using Method.Mail;
using Models.operResult;
using Models.VModels;
using RedisHelper.MailCode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Api.Test.Operate
{
    public class AccountOp
    {
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="pwd"></param>
        /// <param name="mail"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public OperResult<string> UserRegister(string pwd, string mail, string code)
        {
            //判断密码
            if (pwd.Length < 6)
            {
                return OperResult<string>.Failed("密码长度必须大于6位");
            }
            //判断邮箱
            if (!JudgeMail.CheckEmail(mail))
            {
                return OperResult<string>.Failed("邮箱格式不正确");
            }
            //判断邮箱验证码是否存在
            var codeNew = new Code().SelectCode(mail);
            if (codeNew is null)
            {
                return OperResult<string>.Failed("验证码输入错误");
            }
            if (codeNew.ToLower() != code.ToLower())
            {
                return OperResult<string>.Failed("验证码输入错误");
            }

            using (ArticeContext context = new ArticeContext())
            {
                var Account = new Account()
                {
                    Password = pwd,
                    Mail = mail,
                    RegisterTime = GetDateID.getDateId,
                    Level = 0
                };
                context.Accounts.Add(Account);
                if (context.SaveChanges() is 1)
                {
                    context.Entry(Account);
                    return OperResult<string>.Succeed(Account.Id.ToString());
                }
                else
                {
                    return OperResult<string>.Failed("网络错误,请稍后重试");
                }
            }


            return null;
        }

        /// <summary>
        /// 发送邮箱验证码
        /// </summary>
        /// <param name="mail"></param>
        /// <returns></returns>
        public OperResult SendMailCode(string mail)
        {
            //判断邮箱是否合法
            if (!JudgeMail.CheckEmail(mail))
            {
                return OperResult.Failed("邮箱格式不正确");
            }
            //发送邮箱
            var code = SendMail.Send(mail);
            //将验证码持久化(存放在Redis中)
            if (new Code().InsertCode(mail, code))
            {
                return OperResult.Succeed();
            }
            else
            {
                return OperResult.Failed("网络错误,请稍后重试");
            }
        }
    }
}
